package com.copro.chemdb.stat.rule;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.ihelpuoo.db.sql.SQLSegment;
import org.ihelpuoo.lang.StringUtils;
import org.ihelpuoo.util.Properties;

import com.copro.chemdb.stat.AbstractStatRule;
import com.copro.chemdb.stat.StatResult;
import com.copro.chemdb.subject.Subject;
import com.copro.simple.Application;
import com.copro.simple.SimpleException;

public class Rule2 extends AbstractStatRule {
	private Properties conf;

	@Override
	public StatResult doStat(Application app, Subject subject, int type)
			throws SimpleException {
		StatResult statResult = new StatResult();
		SQLSegment sql = app.getSQL("rule2CountAnswer");
		List<String> areaTitles = new ArrayList<String>();
		List<Integer> areaValues = new ArrayList<Integer>();
		sql.set("subjectId", subject.getId());
		sql.set("type", type);
		String area = conf.getStringTrimed(subject.getCode());
		if (StringUtils.isBlank(area)) {
			area = conf.getStringTrimed("default");
		}
		String[] pairs = area.split("\\|");
		for (int i = 0; i < pairs.length; i++) {
			String[] pair = pairs[i].split(",");
			if (StringUtils.isEmpty(pair[0]) && !StringUtils.isEmpty(pair[1])) {
				sql.set("min", Integer.MIN_VALUE);
				sql.set("max", Integer.parseInt(pair[1]));
				areaTitles.add("小于等于" + pair[1]);
			} else if (!StringUtils.isEmpty(pair[0])
					&& (pair.length == 1 || StringUtils.isEmpty(pair[1]))) {
				sql.set("min", Integer.parseInt(pair[0]));
				sql.set("max", Integer.MAX_VALUE);
				areaTitles.add("大于等于" + pair[0]);
			} else {
				sql.set("min", Integer.parseInt(pair[0]));
				sql.set("max", Integer.parseInt(pair[1]));
				areaTitles.add(pair[0] + " ~ " + pair[1]);
			}
			areaValues.add(new Integer(app.getCount(sql.toString())));
		}

		Map<String, Object> result = new HashMap<String, Object>();
		result.put("text", subject.getBrief());
		result.put("areaTitles", areaTitles);
		result.put("areaValues", areaValues);
		statResult.setResult(result);
		statResult.setForwardName("rule2");
		return statResult;
	}

	@Override
	public void setup(Properties conf) {
		this.conf = conf;
	}

}
